package model

import (
	"errors"
	"time"
)

type Question struct {
	Id         int64
	Type       int32
	CreatedAt  time.Time `xorm:"created"`
	UpdatedAt  time.Time `xorm:"updated"`
	Stem       string    `xorm:"text"`
	Answer     string    `xorm:"text"`
	Explain    string    `xorm:"text"`
	ExpPic     string
	Pic        string
	Selections map[string]string
}

func (q *Question) SomeAsc(ids []int64) ([]Question, error) {
	var questions []Question
	err := orm.In("id", ids).Asc("id").Find(&questions)
	return questions, err
}

func (q *Question) SomeDesc(ids []int64) ([]Question, error) {
	var question []Question
	err := orm.In("id", ids).Desc("id").Find(&question)
	return question, err
}

func (q *Question) OneById() error {
	ok, err := orm.ID(q.Id).Get(q)
	if !ok {
		return errors.New(QuestionNotFound)
	}
	return err
}

func (q *Question) SomeLike(stem string) ([]Question, error) {
	var question []Question
	err := orm.Where("stem LIKE ?", "%"+stem+"%").Find(&question)
	return question, err
}

func (q *Question) Create() error {
	ok, err := orm.Insert(q)
	if ok == 0 {
		return errors.New(QuestionCreateFailed)
	}
	return err
}

func (q *Question) Update() error {
	ok, err := orm.ID(q.Id).Cols("stem", "pic", "answer", "selections", "explain", "exp_pic").Update(q)
	if ok == 0 {
		return errors.New(QuestionUpdateFailed)
	}
	return err
}

func (q *Question) PicList(num, size int32) ([]Question, error) {
	length := int(size)
	start := (int(num) - 1) * length
	if length == 0 {
		length = 5
	}
	var questions []Question
	o := orm.Limit(length, start).Where("pic != ?", "").Or("exp_pic != ?","").Asc("id")
	err := o.Find(&questions)
	return questions, err
}

func (q *Question) CountPic() (int64, error) {
	return orm.Where("pic != ?", "").Or("exp_pic != ?","").Count(q)
}

func (q *Question) Page(num, size int32, desc bool, order string) ([]Question, error) {
	length := int(size)
	start := (int(num) - 1) * length
	if length == 0 {
		length = 5
	}
	var questions []Question
	o := orm.Limit(length, start)
	if order == "" {
		order = "id"
	}
	if desc {
		o.Desc(order)
	} else {
		o.Asc(order)
	}
	err := o.Find(&questions)
	return questions, err
}

func (q *Question) CountAll() (int64, error) {
	return orm.Count(q)
}

func (q *Question) Count() (int64, error) {
	return orm.Where("enable = ?", true).Count(q)
}
